﻿using HDS.Common.Helper;
using HDS.Model.Entity.Sys;
using SqlSugar;
using System;
using DbType = SqlSugar.DbType;

namespace HDS.Data
{
    public class SysDbContext
    {
        public SqlSugarScope Db;

        public SysDbContext(string configId = "Sys")
        {
            Db = new SqlSugarScope(new ConnectionConfig()
            {
                ConfigId = configId,
                ConnectionString = AppSettings.GetAppSettingValue(new string[] { "ConnectionStrings", configId }),
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                // Check out more information: https://github.com/anjoy8/Blog.Core/issues/122
                //IsShardSameThread = false,
                AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, pars) =>
                    {
#if DEBUG
                        string keys = "【SQL参数】：";
                        foreach (var param in pars)
                        {
                            keys += $"{param.ParameterName}:{param.Value}\n";
                        }
                        Console.WriteLine("SQL：" + keys + "【SQL语句】：" + sql);
#endif
                    }
                },
                MoreSettings = new ConnMoreSettings()
                {
                    //IsAutoRemoveDataCache = true,
                    DisableNvarchar = true
                },
                InitKeyType = InitKeyType.Attribute
            });
        }

        public ISimpleClient<SysUser> SysUser => Db.GetSimpleClient<SysUser>();
        public ISimpleClient<SysRole> SysRole => Db.GetSimpleClient<SysRole>();
        public ISimpleClient<SysFun> SysFun => Db.GetSimpleClient<SysFun>();
        public ISimpleClient<SysRoleFun> SysRoleFun => Db.GetSimpleClient<SysRoleFun>();
        public ISimpleClient<SysUserRole> SysUserRole => Db.GetSimpleClient<SysUserRole>();
    }
}
